﻿using System.IO;
using System.Runtime.Serialization.Formatters.Binary;

namespace Api.Common
{
    /// <summary>
    /// 深克隆一个对象
    /// </summary>
    /// <typeparam name="T"></typeparam>
    public class CloneHelper<T> where T : class
    {
        public T Clone()
        {
            MemoryStream stream = new MemoryStream();
            BinaryFormatter formatter = new BinaryFormatter();
            formatter.Serialize(stream, this);
            stream.Position = 0;
            return formatter.Deserialize(stream) as T;
        }
    }

    /// <summary>
    /// 定义所有object对象都拥有一个Clone方法
    /// </summary>
    public static class CloneExtend
    {
        /// <summary>
        /// 深克隆
        /// </summary>
        /// <param name="t"></param>
        /// <returns></returns>
        public static object Clone(this object t)
        {
            MemoryStream stream = new MemoryStream();
            BinaryFormatter formatter = new BinaryFormatter();
            formatter.Serialize(stream, t);
            stream.Position = 0;
            return formatter.Deserialize(stream);
        }
    }
}
